<?php


class Ext_Queue_Server
{

    public function __construct( $params )
    {
        $this->params = $params;
        $broker = $params[ 'broker' ];
        $queue = $params[ 'queue' ];
        $this->queue = new Ext_Queue( $broker, $queue );
    }

    public function setClass( $className, $arg = null )
    {
        $this->className = $className;
        $this->classArgs = $arg;
    }

    public function handle()
    {
        $msg = $this->queue->dequeue()->body;
        $message = new Ext_Queue_ExecMessage( $msg );
        $name = $message->getFunction();
        $arguments = $message->getArguments();
        
        if ( in_array( $name, get_class_methods( $this->className ) ) ) {
            $server = new $this->className( $this->classArgs );
            if ( method_exists( $server, 'setQueueParams' ) ) {
                $server->setQueueParams( $this->params );
            }
            try {
                $ret = call_user_func_array( array( 
                                $server, 
                                $name 
                ), $arguments );
            } catch( Exception $e ) {
                $ret = new Ext_Error( $e->getMessage() . " " . $e->getTraceAsString() );
            }
        } else {
            $ret = new Ext_Error( 'Invalid Method' );
        }
        try {
            $this->queue->ackMessage();
        } catch( Exception $e ) {}
        
        if ( Ext_Error::isError( $ret ) ) {
            header( 'error : error' );
            header( "ErrorMessage : " . str_replace("\r", "", str_replace("\n", "", $ret->getMessage() )));
        } else {
            header( 'ok : ok' );
        }
        // Imprimo el mensaje de entrada para que siga su curso.
        header( 'msg : ' . $msg );
        print( $msg );
        
        return;
    }

}
